package net.guoyixian.admin.controller.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;
import net.guoyixian.admin.controller.BaseController;
import net.guoyixian.common.web.FileUtils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class ImgUploadDemoController extends BaseController {
	/**
	 * 这里处理图片上传
	 * 
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "imgUploadTest")
	@ResponseBody
	public Map imgUploadTest(
			@RequestParam(value = "img", required = false) MultipartFile file,
			HttpServletRequest request) throws Exception {
		// 获得物理路径webapp所在路径
		String pathRoot = request.getSession().getServletContext().getRealPath("/");
		
		if (!file.isEmpty()) {
			String contentType = file.getContentType();
			// 获得文件后缀名称
			String imageName = contentType
					.substring(contentType.indexOf("/") + 1);
			String[] filetypes = { "gif", "jpeg", "jpg", "png", "GIF", "JPEG",
					"JPG", "PNG" };
			if (Arrays.asList(filetypes).contains(imageName)) {// 如果包含了允许上传的文件
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				String path = FileUtils.baseImgPath + uuid + "." + imageName;
				// 判断文件是否存在，如果不存在就创建新的文件
				File targetFile = new File(pathRoot + path);
				if (!targetFile.exists()) {
					if(!targetFile.getParentFile().exists()){
						targetFile.getParentFile().mkdirs();
					}
					targetFile.createNewFile();
				}
				file.transferTo(targetFile);
				
				BufferedImage sourceImg =ImageIO.read(new FileInputStream(targetFile));   
				
				Map map = new HashMap();
				map.put("status", "success");
				map.put("url", path);
				map.put("width", sourceImg.getWidth());// 返回的图片宽度
				map.put("height", sourceImg.getHeight());// 返回的图片高度
				return map;
			} else {
				Map map = new HashMap();
				map.put("status", "error");
				map.put("message", "上传文件格式不正确,请选择图片！");
				return map;
			}
		} else {
			Map map = new HashMap();
			map.put("status", "error");
			map.put("message", "文件不存在！");
			return map;
		}

	}

	/**
	 * 这里处理图片裁剪
	 * 
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 * 
	 * imgW原图宽度
	 * imgH原图高度
	 * imgY1坐标Y高度
	 * imgX1坐标X宽度
	 * cropW目标的图片宽度
	 * cropH目标的图片高度
	 * 
	 */
	@RequestMapping(value = "imgCropTest")
	@ResponseBody
	public Map imgCropTest(String imgUrl, Integer imgInitW, Integer imgInitH,
			Integer imgW, Integer imgH, Integer imgY1, Integer imgX1,
			Integer cropW, Integer cropH, HttpServletRequest request)
			throws IOException {
		
		String pathRoot = request.getSession().getServletContext()
				.getRealPath("/");
		//原图全路径
		String sourceImgUrl = pathRoot+imgUrl;
		//临时图片路径
		String tempImgUrl = FileUtils.baseImgPath + UUID.randomUUID().toString().replaceAll("-", "") + "." + imgUrl.substring(imgUrl.lastIndexOf(".")+1);
		//剪切后图片路径
		String targetImgUrl = FileUtils.baseImgPath + UUID.randomUUID().toString().replaceAll("-", "") + "." + imgUrl.substring(imgUrl.lastIndexOf(".")+1);
			
		// 判断文件是否存在，如果不存在就创建新的文件
		File tempImg = new File(pathRoot+tempImgUrl);
		if (!tempImg.exists()) {
			if(!tempImg.getParentFile().exists()){
				tempImg.getParentFile().mkdirs();
			}
		}
		
		//将原图转为显示的尺寸
		Thumbnails.of(sourceImgUrl)//获取原图
				  .size(imgW, imgH)//按照指定大小进行缩放
				  .keepAspectRatio(false)//不按照比例
				  .toFile(tempImg);
		//剪切为需要的尺寸
		Thumbnails.of(tempImg)
				.sourceRegion(imgX1, imgY1, cropW, cropH)
				.size(cropW, cropH)
				.keepAspectRatio(false)
				.toFile(pathRoot+targetImgUrl);
		//删除临时图
		if(tempImg.exists()){
			tempImg.delete();
		}
		
		Map map = new HashMap();
		map.put("status", "success");
		map.put("url", targetImgUrl);

		return map;
	}
}